//
//  HMNavigationController.swift
//  Weibo
//
//  Created by Apple on 2017/6/3.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
//  自定义导航视图控制器，目的需要指定当前导航控制器里面有几个子视图控制器
class HMNavigationController: UINavigationController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        //  设置边缘收拾代理
        self.interactivePopGestureRecognizer?.delegate = self
    }

    //  拦截push操作
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        
        if viewControllers.count > 0 {
            if viewControllers.count == 1 {
                //  获取上一级控制器标题
                let title = viewControllers.first!.title!
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
            } else {
                //  根视图不需要返回，第三级控制器及以后才需要设置返回
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
            }
            //  设置标题
            viewController.title = "当前显示的第\(viewControllers.count + 1)级控制器"
            //  隐藏底部toolbar，设置这句代码puhs的时候会有黑影
            //  解决办法1.设置tabbar的背景图片
            //  解决办法2.设置window的背景色
            viewController.hidesBottomBarWhenPushed = true
        }
        
        
        super.pushViewController(viewController, animated: animated)
        
        
        
    }
    
    @objc private func backAction() {
        //  pop到上一级控制器
        self.popViewController(animated: true)
    }
    
    
    //  MARK: -- UIGestureRecognizerDelegate
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if viewControllers.count == 1 {
            //  根视图控制器不开启，否则push卡死界面
            return false
        }
        //  是否开启边缘收拾
        return true
    }

}
